
const opts = {
  wdth: 100, // canvas size
  height: 100,
  top: 20, // 左上角
  left: 20,
  segment: 4, // 刻度小线段的长度
  interval_x: 1, // 轴刻度间隔 // 厘米
  interval_y: 1
}

// const pixel_2_cm = 2.54 / 96 // 1像素对应的长度
const cm_2_pixel = 96 / 2.54 // 1厘米对应的pixel

function setRule(ctx, options) {
  const { width, height, top, left, segment, cm_x, cm_y } = options

  const interval_x = cm_2_pixel * (cm_x || 1)
  const interval_y = cm_2_pixel * (cm_y || 1)

  ctx.clearRect(0, 0, width, height)

  ctx.save()

  ctx.strokeStyle = 'red'
  ctx.fillStyle = 'red'
  ctx.textBaseline = 'bottom'

  ctx.beginPath()
  ctx.moveTo(left, top)
  ctx.lineTo(width, top)
  ctx.moveTo(left, top)
  ctx.lineTo(left, height)
  ctx.fill()
  ctx.stroke()
  ctx.closePath()

  // x轴刻度
  const segmentTop = top - segment // 小线段上部的长度
  const dot = 2 // 文字偏移 // 文字里轴的距离

  for (let i = 0; (left + i * interval_x) <= width - left; i++) {
    ctx.moveTo(left + i * interval_x, segmentTop)
    ctx.lineTo(left + i * interval_x, top)

    ctx.fillText(i * cm_x, left + i * interval_x + dot, top - dot)
  }
  // y轴刻度
  ctx.textBaseline = 'top'
  ctx.textAlign = 'end'

  const segmentLeft = left - segment
  for (let i = 0; (top + i * interval_y) <= height - top; i++) {
    ctx.moveTo(segmentLeft, top + i * interval_y)
    ctx.lineTo(left, top + i * interval_y)

    ctx.fillText(i * cm_y, left - dot - 2, top + i * interval_y + dot)
  }
  ctx.stroke()

  ctx.restore()
}

export { setRule }
